package com.gitee.xhs.keyedState.aggregatingState;

import com.gitee.xhs.sampleRecod.transactionRecord.Transaction;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * @author BigHead
 * @date 2022/6/30 14:49
 * @description AggregateFunctionDao
 */
public class AggregateFunctionDao implements Serializable {

    private final Map<Double, Integer> amountUniqueCountMap = new HashMap<>();

    public Map<Double, Integer> getAmountUniqueCountMap() {
        return amountUniqueCountMap;
    }

    public synchronized void add(Transaction transaction) {
        if (amountUniqueCountMap.containsKey(transaction.getAmount())) {
            amountUniqueCountMap.put(
                    transaction.getAmount(),
                    amountUniqueCountMap.get(transaction.getAmount()) + 1
            );
        } else {
            amountUniqueCountMap.put(
                    transaction.getAmount(),
                    1
            );
        }
    }

    public synchronized void merge(AggregateFunctionDao aggregateFunctionDao) {
        Map<Double, Integer> mergeMap = aggregateFunctionDao.getAmountUniqueCountMap();

        for (Double uniqueKey : mergeMap.keySet()) {
            if (amountUniqueCountMap.containsKey(uniqueKey)) {
                amountUniqueCountMap.put(
                        uniqueKey,
                        amountUniqueCountMap.get(uniqueKey) + mergeMap.get(uniqueKey)
                );
            } else {
                amountUniqueCountMap.put(
                        uniqueKey,
                        mergeMap.get(uniqueKey)
                );
            }
        }

    }

}
